package cn.gzsxt.interceptor;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 作用：用于拦截除了登录、注销以外的所有操作，
 * 判断该操作，当前登录的管理员是否有权限，如果有权限就允许操作，没有权限就不允许操作
 * @author ranger
 *
 */
public class PermissionHandlerInterceptor implements HandlerInterceptor {
	
	private static final Logger LOGGER=LogManager.getLogger(PermissionHandlerInterceptor.class);

	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//第一步：获得当前管理员的信息
		HttpSession session = request.getSession();
		Map<String, Object> admin =(Map<String, Object>) session.getAttribute("admin");
		Map<String, Object> role = (Map<String, Object>)admin.get("role");
		List<Map<String, Object>> permisssions = (List<Map<String, Object>>)role.get("permisssions");
		
		//第二步：获得请求路径
		String requestURI = request.getRequestURI();
//		StringBuilder builder=new StringBuilder(requestURI);
//		builder.delete(0,request.getContextPath().length());
//		String path=builder.toString();
		//LOGGER.debug("请求路径："+request.getRequestURI()+"，权限路径："+path);
		
		//第三步：将当前的路径放在session里面
		//问题：问题为什么当前路径放在session里面
		//答：因为seesion具有穿透性。而requetst只能传递给下一个对象。所以在拦截器设置的request是传递不回到页面
		session.setAttribute("path", requestURI);
		
		for (Map<String, Object> permisssion : permisssions) {
			//使用请求路径是否包含配置路径
			
			//判断是否包含
			if(requestURI.contains((String)permisssion.get("PERMISSION_ACTION"))){
				return true;
			}
		}
		request.setAttribute("admin_login_msg", "您没有操作该功能的权限，请求先授权");
		request.getRequestDispatcher("/login.jsp").forward(request, response);
		return false;
	}
	

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}

}
